package cn.jhc.teachingquality.loader;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;

import com.android.volley.toolbox.RequestFuture;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import cn.jhc.teachingquality.Global;
import cn.jhc.teachingquality.bean.Student;
import cn.jhc.teachingquality.bean.TeachingLog;
import cn.jhc.teachingquality.net.RequestQueueFactory;
import cn.jhc.teachingquality.net.teaching.FetchStudentsRequest;

/**
 * Created by luyanfei on 16-4-18.
 */
public class StudentsAsyncLoader extends AsyncTaskLoader<List<Student>> {

    private TeachingLog teachingLog;

    public StudentsAsyncLoader(Context context, TeachingLog teachingLog) {
        super(context);
        this.teachingLog = teachingLog;
    }

    @Override
    public List<Student> loadInBackground() {
        RequestFuture<JSONArray> future = RequestFuture.newFuture();
        FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest(teachingLog.getHiddenId(),future);
        RequestQueueFactory.getRequestQueue(getContext()).add(fetchStudentsRequest);
        JSONArray jsonArray;
        try {
            jsonArray = future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        List<Student> students = new ArrayList<>();
        try {
            for(int i=0; i<jsonArray.length(); i++){
                JSONArray innerArray = jsonArray.getJSONArray(i);
                Student student = new Student(innerArray.getString(0), innerArray.getString(2));
                students.add(student);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return students;
    }
}
